/*
 * Class PlayerOption2
 *
 * Version 1.0
 *
 * Friday, August 22, 2008
 *
 * Created by Palidino76
 */

package palidino76.rs2.io.packets;

import palidino76.rs2.*;
import palidino76.rs2.player.Player;
import palidino76.rs2.util.Misc;

public class PlayerOption2 implements Packet {
    /**
     * Handles the second player option.
     * @param p The Player which the frame should be handled for.
     * @param packetId The packet id this belongs to.
     * @param packetSize The amount of bytes being recieved for this packet.
     */
    public void handlePacket(Player p, int packetId, int packetSize) {
        if (p == null || p.stream == null) {
            return;
        }
        if (!p.playerOption2) {
            int playerId = p.stream.readUnsignedWord();
            if (playerId <= 0 || playerId >= Engine.players.length || Engine.players[playerId] == null) {
                return;
            }
            p.clickId = playerId;
            p.clickX = Engine.players[playerId].absX;
            p.clickY = Engine.players[playerId].absY;
            if (Misc.getDistance(p.absX, p.absY, p.clickX, p.clickY) > 30) {
                return;
            }
            p.playerOption2 = true;		
        }
        if (p.clickId <= 0 || p.clickId >= Engine.players.length || Engine.players[p.clickId] == null) {
            p.playerOption2 = false;
            return;
        }
        if (Misc.getDistance(p.absX, p.absY, p.clickX, p.clickY) > 1) {
            return;
        }
        Player p2 = Engine.players[p.clickId];
        if (p2.pTrade.getPartner() == p) {
        } else {
            p.frames.sendMessage(p, "Sending trade request...");
            p.frames.sendMessage(p2, p.username.substring(0, 1).toUpperCase() + p.username.substring(1) + ":tradereq:");
        }
        p.requestFaceTo(p.clickId);
        p.pTrade.tradePlayer(p2);
        p.playerOption2 = false;
	/*p.followId = p.stream.readUnsignedWordA();
	Player en = Engine.players[p.followId];

	    if (p.freezeDelay == 0) {
			int n;
			n = en.absY - p.absY; // This will get updated in process.
		if ((en.absX - p.absX) <= (n * (-1)) && (en.absX - p.absX) >= (n - 1)) {
		    if (n < 0) {
			p.WalkingTo(en.absX, en.absY + 1);
		    }
		    if (n > 0) {
			p.WalkingTo(en.absX, en.absY - 1);
		    }
		} else if ((en.absX - p.absX) > 0) {
			p.WalkingTo(en.absX - 1, en.absY);
		} else if ((en.absX - p.absX) < 0) {
			p.WalkingTo(en.absX + 1, en.absY);
		}
		if (((en.absX - p.absX) == 0) && (n < 0)) {
			p.WalkingTo(en.absX, en.absY + 1);
		}
		if (((en.absX - p.absX) == 0) && (n >= 0)) {
			p.WalkingTo(en.absX, en.absY - 1);
		}
		if (en.absX - p.absX > 12 || p.absX - en.absX > 12 ||en.absY - p.absY > 12 || p.absY - en.absY > 12) {
			p.WalkingTo(p.absX, p.absY); // Reset walking if the other player is further then 12 squares (To prevent the following if p2 teleports away)
		}
	    }*/
    }
}
